import Vue from 'vue'
import VueRouter from 'vue-router'
import Register from '../views/Register.vue'
import Login from '../views/Login.vue'
import UserInfo from '../views/UserInfo.vue'
import Edit from '../views/Edit.vue'
import Home from '../views/Home.vue'
import Article from '../views/Article.vue'
import EditCategory from '../views/EditCategory.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Home,
    meta: {
      keepalive: true
    }
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/userinfo',
    component: UserInfo,
    meta: {
      istoken: true
    }
  },
  {
    path: '/edit',
    component: Edit,
    meta: {
      istoken: true
    }
  },
  {
    path: '/editcategory',
    component: EditCategory
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // console.log(to)
  /* if (!localStorage.getItem('token') && !localStorage.getItem('id') && to.meta.istoken) {
    return next('/login')
  }
  next() */
  if (to.meta.istoken) {
    if (!localStorage.getItem('token') || !localStorage.getItem('id')) {
      next('/login')
      return Vue.prototype.$msg.fail('请重新登录')
    }
  }
  next()
})

export default router
